package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.interfaces.CWaybillAddressService;
import cn.huiyunche.base.service.mappers.CWaybillAddressMapper;
import cn.huiyunche.base.service.model.CWaybillAddress;
import cn.huiyunche.base.service.model.CWaybillAddressExample;
import cn.huiyunche.tools.basic.Collections3;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import com.alibaba.fastjson.JSON;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 运单地址 接口实现类
 *
 * @author lm
 */
@Service
public class CWaybillAddressServiceImpl implements CWaybillAddressService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CWaybillAddressServiceImpl.class);

    @Autowired
    private CWaybillAddressMapper cWaybillAddressMapper = null;

    private CWaybillAddressMapper getCWaybillAddressMapper() {
        return this.cWaybillAddressMapper;
    }

    /**
     * 创建运单 添加运单地址
     *
     * @param cWaybillAddress
     */
    @Override
    public int addAddress(CWaybillAddress cWaybillAddress) {
        LOGGER.info("insert address info params cWaybillAddress : {}.", cWaybillAddress);
        try {
            return this.getCWaybillAddressMapper().insertSelective(cWaybillAddress);
        } catch (Exception e) {
            LOGGER.error("insert address info params cWaybillAddress : {}, {}", cWaybillAddress, e);
            throw new BusinessException("添加运单地址异常");
        }
    }

    @Override
    public CWaybillAddress getByWaybillid(Long waybillid) {
        LOGGER.info("getByWaybillid param : {}", waybillid);
        CWaybillAddressExample cWaybillAddressExample = new CWaybillAddressExample();
        cWaybillAddressExample.createCriteria().andWaybillIdEqualTo(waybillid);
        List<CWaybillAddress> addresses = cWaybillAddressMapper.selectByExample(cWaybillAddressExample);
        if (Collections3.isNotEmpty(addresses)) {
            return addresses.get(0);
        }
        return null;
    }

    /**
     * 查询运单地址信息
     *
     * @param addressExample
     */
    @Override
    public CWaybillAddress selectByExample(CWaybillAddressExample example) {
        LOGGER.info("select cwaybill address params example : {}", JSON.toJSONString(example));
        try {
            List<CWaybillAddress> addresses = this.getCWaybillAddressMapper().selectByExample(example);
            if (CollectionUtils.isNotEmpty(addresses)) {
                return addresses.get(0);
            }
        } catch (Exception e) {
            LOGGER.error("select cwaybill address error : {}.", e);
            throw new BusinessException("查询运单地址异常");
        }
        return null;
    }

}